from django.db import models
from mptt.models import MPTTModel

from amat_app.utils import PlatformChoices, AppiumDriverChoices


class AppiumConfigModel(models.Model):
    """Appium 所需的通用设置,通常为一个项目中不变的参数"""
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=255, default='', verbose_name="配置名称")
    platformName = models.CharField(max_length=20, choices=PlatformChoices.choices, verbose_name="platformName")
    platformVersion = models.CharField(max_length=20, blank=True, null=True, default='',
                                       verbose_name="platformVersion")

    automationName = models.CharField(max_length=255, choices=AppiumDriverChoices.choices,
                                      default=AppiumDriverChoices.UiAutomator2,
                                      verbose_name="automationName")
    appPackage = models.CharField(max_length=255, null=False, default='', verbose_name="appPackage")
    appActivity = models.CharField(max_length=255, null=False, default='', verbose_name="appActivity")

    extra_params = models.JSONField(default=dict, blank=True, null=True, verbose_name="额外参数")

    class Meta:
        verbose_name = "Appium 配置"
        verbose_name_plural = "Appium 配置"

    def __str__(self):
        return self.name


class ProjectModel(models.Model):
    """测试项目，包含固定的 Appium 设置"""
    name = models.CharField(max_length=255, verbose_name="项目名称")
    description = models.TextField(blank=True, null=True, verbose_name="项目描述")
    appium_config = models.ForeignKey(
        AppiumConfigModel, on_delete=models.CASCADE, related_name='project', verbose_name="Appium 配置",
    )
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    last_updated_at = models.DateTimeField(auto_now=True, verbose_name="最近更新时间")

    class Meta:
        verbose_name = "测试项目"
        verbose_name_plural = "测试项目"

    def __str__(self):
        return self.name


class DeviceModel(models.Model):
    udid = models.CharField(max_length=255, blank=True, null=True, unique=True)
    name = models.CharField(max_length=255, blank=True, null=True)
    imei = models.CharField(max_length=255, blank=True, null=True)
    status = models.CharField(max_length=255, blank=True, null=True)

    def __str__(self):
        return self.udid


# class SectionModel(models.Model):
#     name = models.CharField(max_length=255, blank=True, null=True, verbose_name="模块名称")
#     parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='sub_sections')
#
#     def __str__(self):
#         return self.name

class SectionModel(models.Model):
    name = models.CharField(max_length=255, blank=True, null=True, verbose_name="模块名称")
    parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='subSections')

    class Meta:
        verbose_name = "模块"
        verbose_name_plural = "模块"

    def __str__(self):
        return self.name


class CaseModel(models.Model):
    name = models.CharField(max_length=255, blank=True, null=True, verbose_name="用例名称")
    description = models.TextField(blank=True, null=True, verbose_name="用例描述")
    section = models.ForeignKey(SectionModel, related_name="cases", on_delete=models.CASCADE, verbose_name="所属模块")
    priority = models.IntegerField(blank=True, null=True, verbose_name="优先级")
    preCondition = models.TextField(blank=True, null=True, verbose_name="前置条件")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")

    def __str__(self):
        return self.name


class CaseStepModel(models.Model):
    case = models.ForeignKey(CaseModel,
                             on_delete=models.CASCADE,
                             verbose_name="用例步骤",
                             related_name="steps")
    order = models.IntegerField(blank=True, null=True, verbose_name="测试顺序")
    stepName = models.CharField(max_length=255, blank=True, null=True, verbose_name="步骤描述")
    expected = models.TextField(blank=True, null=True, verbose_name="预期结果")

    parent = models.ForeignKey(
        'self', on_delete=models.CASCADE, related_name='subSteps',
        blank=True, null=True, verbose_name="父步骤"
    )  # 自关联,实现嵌套step

    class Meta:
        ordering = ['order']

    def __str__(self):
        parent_info = f" (Sub-step of {self.parent.stepName})" if self.parent else ""
        return f"Step {self.order} for {self.case.name}{parent_info}"


class StepResultModel(models.Model):
    step = models.ForeignKey(CaseStepModel, on_delete=models.CASCADE, related_name='results', verbose_name="所属步骤")

    status = models.CharField(max_length=255,
                              blank=True,
                              null=True,
                              verbose_name="结果状态",
                              choices=[('passed', '通过'), ('failed', '失败'), ('skipped', '跳过'), ('error', '异常'),
                                       ('unknown', '未知'), ('blocked', '阻塞'), ('other', '其他')], )
    # 备注
    remark = models.TextField(blank=True, null=True, verbose_name="备注")
    output = models.TextField(blank=True, null=True, verbose_name="输出结果")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")

    def __str__(self):
        return f"Result for {self.step.stepName} - {self.status}"


class TestRunModel(models.Model):
    """用于记录每次测试运行"""
    cases = models.ManyToManyField(CaseModel, related_name='test_runs')
    status = models.CharField(max_length=50,
                              choices=[('wait', 'wait'), ('testing', 'testing'), ('finished', 'finished')])
    started_at = models.DateTimeField(auto_now_add=True)
    name = models.CharField(max_length=255, blank=True, null=True)
    ends_at = models.DateTimeField(blank=True, null=True)

    def __str__(self):
        return f"TestRun {self.name}"

# class TestRunStepResultModel(models.Model):
#     """记录每次测试运行中步骤的执行结果"""
#     test_run = models.ForeignKey(
#         TestRunModel, related_name='step_results', on_delete=models.CASCADE
#     )
#     step = models.ForeignKey(CaseStepModel, on_delete=models.CASCADE)
#     status = models.CharField(max_length=50, choices=[('passed', 'Passed'), ('failed', 'Failed')])
#     actual_result = models.TextField(blank=True, null=True)
#
#     def __str__(self):
#         return f"Result for Step {self.step.stepName} in Run {self.test_run.id}"
